package com.zhima.sdk;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhima.sdk.model.AuthInfo;
import com.zhima.sdk.model.DeviceInfo;
import com.zhima.sdk.model.PhoneInfo;
import com.zhima.sdk.utils.ZMDeviceUtil;
import com.zhima.sdk.utils.ZMEncryptUtil;
import com.zhima.sdk.utils.ZMFileUtil;

import org.json.JSONObject;

import java.io.File;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Bin on 2018/2/4.
 */

public class ZMMgr {

    public static final String PATH_ZMSDK = ".zms";

    public static final String PATH_FILE_DEVICE_ID = PATH_ZMSDK + File.separator + "zmdid";

    private static final String PREFS_FILE = "zm_conf.xml";

    private static final String PREFS_KEY_DID = "k_did";

    private static String deviceId = "";

    private static boolean sdEnable = true;

    private static Context mContext;

    public static void init(Context context, final String appName) {
        mContext = context;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String sdPath = ZMFileUtil.getSDPath();
                    String dPath = sdPath + File.separator + PATH_FILE_DEVICE_ID;
                    if (!TextUtils.isEmpty(sdPath)) {
                        deviceId = getDeviceIdFromSD(dPath);
                    } else {
                        sdEnable = false;
                    }

                    if (TextUtils.isEmpty(deviceId)) {
                        final SharedPreferences prefs = mContext.getSharedPreferences(PREFS_FILE, 0);
                        deviceId = prefs.getString(PREFS_KEY_DID, "");
                    }

                    if (!TextUtils.isEmpty(deviceId)) {
                        return;
                    } else {
                        deviceId = ZMDeviceUtil.getDeviceId(mContext);
                    }

                    if (TextUtils.isEmpty(deviceId)) {
                        return;
                    }


                    DeviceInfo deviceInfo = null;
                    try {
                        deviceInfo = ZMDeviceUtil.getDeviceInfo(mContext);
                    } catch (Exception e) {
                        return;
                    }

                    if (deviceInfo == null) {
                        return;
                    }

                    String userAgent = ZMDeviceUtil.getUserAgent(mContext) + "Lingjiang";
                    if (TextUtils.isEmpty(userAgent)) {
                        return;
                    }

                    if (!ZMDeviceUtil.isConnected(mContext)) {
                        return;
                    }

                    Gson mGson = new Gson();
                    OkHttpClient client = new OkHttpClient();

                    String apiUrl = "http://api.qingjuhe.com";

                    Request request = new Request.Builder()
                            .url(apiUrl + "?_token")
                            .removeHeader("User-Agent")
                            .addHeader("User-Agent", userAgent)
                            .build();
                    Response response = client.newCall(request).execute();
                    String resultData = response.body().string();
                    if (!resultData.contains("token")) {
                        return;
                    }

                    String dataJson = mGson.toJson(deviceInfo);

                    PhoneInfo phoneInfo = new PhoneInfo();
                    String tName = appName == null ? "test":appName;
                    phoneInfo.setAppName(tName);
                    phoneInfo.setDeviceId(deviceId);
                    phoneInfo.setDeviceInfo(dataJson);
                    phoneInfo.setPlatform("android");

                    String __dataJson = mGson.toJson(phoneInfo);


                    AuthInfo authInfo = mGson.fromJson(resultData, AuthInfo.class);

                    RequestBody body = new FormBody.Builder()
                            .add("__data", ZMEncryptUtil.mdEncrypt(__dataJson))
                            .add("__token", authInfo.token)
                            .add("__time", authInfo.time)
                            .add("__ticket", authInfo.ticket)
                            .build();

                    request = new Request.Builder()
                            .url(apiUrl + "/api/phone_sn/add")
                            .removeHeader("User-Agent")
                            .addHeader("User-Agent", userAgent)
                            .addHeader("Authorization", ZMEncryptUtil.getBasicBase64(deviceId))
                            .post(body)
                            .build();


                    response = client.newCall(request).execute();
                    resultData = response.body().string();
                    JSONObject resultJson = new JSONObject(resultData);
                    int ret = resultJson.getInt("ret");
                    if (ret == 0) {
                        saveDeviceIdToSD(dPath, deviceId);
                    } else if (ret == 1) {
                        String code = resultJson.getString("code");
                        if (code.equals("-1")){
                            saveDeviceIdToSD(dPath, deviceId);
                        }
                    }

                } catch (Exception e) {
//                    Log.e("zmerr: ", e.getMessage());
                }
            }
        }).start();


    }


    private static String getDeviceIdFromSD(String dPath) {
        try {
            deviceId = ZMFileUtil.readFile2String(dPath);
            return deviceId;

        } catch (Exception e) {

            return "";
        }
    }

    private static void saveDeviceIdToSD(String dPath, String deviceId) {
        try {
            boolean saveOk = false;
            if (sdEnable) {
                saveOk = ZMFileUtil.writeFileFromString(dPath, deviceId);
            }

            if (!saveOk) {
                saveDeviceIdToAppData(deviceId);
            }
        } catch (Exception e) {
            saveDeviceIdToAppData(deviceId);
        }
    }


    private static void saveDeviceIdToAppData(String deviceId) {
        final SharedPreferences prefs = mContext.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
        prefs.edit().putString(PREFS_KEY_DID, deviceId).apply();
    }


}
